<template>
  <Layout class="articalManager">
      <div>
        <Form ref="form1"  :label-width="120">
            <Row  class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="标题：">
                        <Input class="query-form-el" type="text" v-model="title"></Input>
                    </FormItem>
                </Col>
                <Col span="8" offset="8">
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button  class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" type="success"  class="ivu-btn-add" icon="md-add" @click="addArtical()">新增</Button>
                </Col>
            </Row>
        </Form>
      </div>
      <!-- 响应结果内容展示 -->
      <Table ref='table' :height="tableHeight" :loading="buttonLoading" no-data-text="没有查询到相关数据!"
           stripe border :columns="columns1" :data="resultData">
      </Table>
      <!-- 底部分页条 -->
    <Page :total="dataCount" :page-size="pageSize"
          :page-size-opts="pageSizeArray" @on-change="pageChange"
          @on-page-size-change="pageSizeChange" show-total show-sizer />

    <!--弹出窗  @on-cancel="cancel":当点击取消触发的函数-->
   
       <Modal  title="资料管理" :transfer=false v-model="model1"  :width=800 >
            <Row>
                <Col span="24">
                    <Form ref="formCustom" :model="formCustom" :rules="ruleCustom"  label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="标题" prop="infoTitle">
                                  <Input type="text" v-model="formCustom.infoTitle"></Input>
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" v-show="type=='3'" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="封面图片："  prop="fileName">
                                    <Upload
                                            ref="upload"
                                            type="drag"
                                            multiple
                                            :show-upload-list="true"
                                            :before-upload="beforeUpload"
                                            :action="downloadUrl"
                                            :max-size="10240"
                                    >
                                        <div style="padding: 20px 0">
                                            <Icon type="ios-cloud-upload" size="30" style="color: #3399ff"></Icon>
                                            <p> 请上传 jpg，jpeg，png 格式的图片</p>
                                        </div>
                                    </Upload>
                                    <div v-if="fileName !== null">
                                        附件:  <a  @click.prevent="downloadFile(formCustom.cover,fileName)">{{fileName}}</a>
                                        <Button  type="text" icon="md-trash" @click="deleteFile(formCustom.cover)"  style="margin-left: 20px;margin-bottom: 3px" />
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="center" class="code-row-bg">
                          <Col span="23">
                              <FormItem label="内容" prop="infoContent">
                                  <quill-editor ref="myTextEditor" v-model="formCustom.infoContent"  style="height:240px;margin-bottom: 80px"></quill-editor>
                              </FormItem>
                          </Col>
                        </Row>
                      <!--  <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem>
                                    <Button   class='ivu-btn-save' @click="addOrUpdate()" >确定</Button>
                                    <Button type="text"  class='ivu-btn-cancel'  @click="modalcancel" >取消</Button>
                                </FormItem>
                            </Col>
                        </Row>-->
                    </Form>
                </Col>
            </Row>
           <div slot="footer">
               <Button   class='ivu-btn-save' @click="addOrUpdate()" >确定</Button>
               <Button type="text"  class='ivu-btn-cancel'  @click="modalcancel" >取消</Button>
           </div>
        </Modal>

        <Modal class="modal-view-detail" title="资料管理"   :transfer=false   v-model="model2"  :width=800 >
            <Row>
                <Col span="24">
                    <Form ref="showdata" :label-width="80" >
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="标题" prop="infoTitle">
                                      {{showdata.infoTitle}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="浏览量" prop="browse">
                                      {{showdata.browse}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="创建人" prop="userName">
                                      {{showdata.userName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="创建时间" prop="infoTitle">
                                      {{showdata.createDate}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" v-if="type=='3'&&picture==''" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="附件：" prop="infoId">
                                </FormItem>
                            </Col>
                            <Col span="11">
                            </Col>
                        </Row>
                        <Row type="flex" style="height:150px" v-if="type=='3'&&picture!=''" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="附件：" prop="infoId">
                                    <div  style="width: 300px;height: 100px;">
                                        <img :src="picture"  style="width: 100%;height: 100%;">
                                        <a  @click.prevent="downloadFile(coverId,coverName)">{{fileName}}</a>
                                    </div>
                                </FormItem>
                            </Col>
                            <Col span="11">
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                          <Col span="23">
                              <FormItem label="内容" prop="infoContent">
                                  <div v-html="showdata.infoContent"></div>
                              </FormItem>
                          </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
            </div>
        </Modal>

  </layout>

</template>

<script>
    import {Api} from "../../../api/index.js"
    import {quillEditor} from 'vue-quill-editor'
    import {sessionStorage} from '../../../common/cacheUtils.js';

    export default {
        components: {
            quillEditor
        },
        props: ["type"],
        data() {
            return {
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                formCustom: {},
                ruleCustom: {
                    infoTitle: [{
                        required: true,
                        message: "",
                        trigger: "change"
                    }],
                    infoContent: [{
                        required: true,
                        message: "",
                        trigger: "change"
                    }]
                },
                title: "",
                resultData: [],
                showdata: {},
                tableHeight: '',
                pageSizeArray: [5, 10, 20, 50],
                dataCount: 0,
                pageSize: 5,
                currentPage: 1,
                columns1: [{
                        title: "序号",
                        width: 80,
                        align: "center",
                        render: (h, params) => {
                            return h('span', params.index + (this.currentPage - 1) * this.pageSize + 1);
                        }
                    },
                    {
                        title: '标题',
                        align: 'center',
                        width: 300,
                        ellipsis: true,
                        key: 'infoTitle'
                    },
                    {
                        title: '创建人',
                        align: 'center',
                        width: 130,
                        key: 'userName'
                    },
                    {
                        title: '创建时间',
                        align: 'center',
                        width: 180,
                        key: 'createDate',
                        render: (h, params) => {
                             return h('span', (this.formatDate(new Date(params.row.updateDate), 'yyyy-MM-dd')));
                        }
                    },
                    {
                        title: '内容',
                        align: 'center',
                        ellipsis: true,
                        key: 'infoContent'
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 200,
                        render: (h, params) => {
                            let flag =(this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId  ||
                                ((this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined &&
                                    params.row.orgCode && params.row.orgCode.indexOf(this.currentUser.companyCode)!=-1)
                                ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined))
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color:flag?'':'#c5c8ce',
                                        pointerEvents:flag?'':'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color:flag?'red':'#c5c8ce',
                                        pointerEvents:flag?'':'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    }
                ],
                model1: false,
                model2: false,
                infoId: "",
                file: null,
                buttonLoading:false,
                picture: '',
                fileName: null,
                downloadUrl: Api.downloadMongoFile
            }
        },
        mounted: function() {
            this.tableHeight = window.innerHeight - 325;
            //页面加载执行的查询函数,返回的总条数,激活前端分页插件的页码功能.
            this.query();
        },
        methods: {
            downloadFile(fileId, fileName) {
                let url = this.downloadUrl + "/" + fileId
                this.$http.get(url, {
                    responseType: 'blob' //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.body.type //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            deleteFile(id) {
                this.$http.delete(Api.uploadMongoFile + "/" + id).then((res) => {
                    if (res.data.result == "success") {
                        this.form1datacopy.programmeFile = null;
                        this.fileName = null;
                    }
                }).catch(e => {
                    this.$Message.error("附件上传失败");
                });
            },
            query() {
                this.buttonLoading=true
                this.$http.get(Api.getArticals + "?startPage=" + this.currentPage + "&size=" +
                    this.pageSize + "&infoType=" + this.type).then(res => {
                    if (res.data.status == 200) {
                        this.resultData = res.data.data.data;
                        this.resultData.forEach(item => {
                            item.createDate = this.formatDate(new Date(item.createDate), 'yyyy-MM-dd');
                        })
                        this.buttonLoading=false
                    }
                });
            },
            modalcancel() {
                this.model1 = false;
                this.formCustom = {};
            },
            addOrUpdate() {
                this.$refs["formCustom"].validate((valid) => {
                    if (valid) {
                        this.formCustom.createUserId = sessionStorage('userId').getObject('userId').userId;
                        this.formCustom.orgId = sessionStorage('userId').getObject('userId').orgId;
                        this.formCustom.updateUserId = sessionStorage('userId').getObject('userId').userId;
                        if (this.formCustom.infoId == "") {
                            if (this.file != null) {
                                const file = this.file;
                                let formData = new FormData();
                                formData.append("file", file);
                                this.$http.put(Api.uploadMongoFile, formData).then((res) => {
                                    if (res.data.result == "success") {
                                        this.formCustom.cover = res.data.id;
                                        this.$http.post(Api.addArtical, this.formCustom).then((res) => {
                                            if (res.data.status == 200) {
                                                this.query();
                                                this.model1 = false;
                                                this.$Message.info('添加成功');
                                            } else {
                                                this.$Message.error("修改失败");
                                            }
                                        })
                                    }
                                }).catch(e => {
                                    this.$Message.error("修改失败");
                                });
                            } else {
                                this.$http.post(Api.addArtical, this.formCustom).then((res) => {
                                    if (res.data.status == 200) {
                                        this.query();
                                        this.model1 = false;
                                        this.$Message.info('添加成功');
                                    } else {
                                        this.$Message.error("修改失败");
                                    }
                                }).catch(e => {
                                    this.$Message.error("修改失败");
                                });
                            }
                        } else {
                            if (this.file != null) {
                                const file = this.file;
                                let formData = new FormData();
                                formData.append("file", file);
                                this.$http.put(Api.uploadMongoFile, formData).then((res) => {
                                    if (res.data.result == "success") {
                                        this.formCustom.cover = res.data.id;
                                        this.$http.post(Api.updateArtical, this.formCustom).then((res) => {
                                            if (res.data.status == 200) {
                                                this.query();
                                                this.model1 = false;
                                                this.$Message.info('修改成功');
                                            } else {
                                                this.$Message.error("修改失败");
                                            }
                                        }).catch(e => {
                                            this.$Message.error("修改失败");
                                        });
                                    }
                                }).catch(e => {
                                    this.$Message.error("修改失败");
                                });
                            } else {
                                this.$http.post(Api.updateArtical, this.formCustom).then((res) => {
                                    if (res.data.status == 200) {
                                        this.query();
                                        this.model1 = false;
                                        this.$Message.info('修改成功');
                                    } else {
                                        this.$Message.error("修改失败");
                                    }
                                }).catch(e => {
                                    this.$Message.error("修改失败");
                                });
                            }
                        }
                    }
                })
            },
            addArtical() {
                this.formCustom = {
                    infoId: "",
                    infoTitle: "",
                    infoContent: "",
                    infoType: this.type
                }
                this.model1 = true;
            },
            beforeUpload(file) {
                this.file = file;
                this.fileName = file.name;
                return false;
            },
            //重置输入框
            reset() {
                this.title = '';
            },
            pageChange(pageNum) {
                this.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pageSize = pageSize;
                this.query();
            },
            showData(data, flag) {
                this.picture  = "";
                if(data.row.cover != null){
                    let url = Api.getMongoFileInfo + '/' + data.row.cover;
                    this.$http.get(url, {
                        params: {}
                    }).then((res) => {
                        if(res.data)
                        this.picture = res.data.picture;
                        this.fileName = res.data.fileName;
                        this.downloadUrl = Api.downloadMongoFile + '/' + res.data.cover;
                    }).catch(e => {
                        this.$Message.error("数据获取失败")
                    })
                }
                if (flag == 1) {

                    this.showdata = data.row;
                    this.showdata.createDate = this.formatDate(new Date(this.showdata.createDate), 'yyyy-MM-dd');
                    this.showdata.updateDate = this.formatDate(new Date(this.showdata.updateDate), 'yyyy-MM-dd');
                    this.model2 = true;
                } else {
                    //修改页面
                    this.add = false;
                    this.formCustom = data.row;
                    this.formCustom.createDate = this.formatDate(new Date(this.formCustom.createDate), 'yyyy-MM-dd');
                    this.formCustom.updateDate = this.formatDate(new Date(this.formCustom.updateDate), 'yyyy-MM-dd');
                    this.model1 = true;
                }
            },
            deleteData(params) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否确定删除？</p>',
                    onOk: () => {
                        this.$http.delete(Api.deleteArtical + '/' + params.row.infoId).then((res) => {
                            if (res.data.status == 200) {
                                this.$Message.info('删除成功');
                                this.query();
                            } else {
                                this.$Message.info('删除失败');
                            }
                        }).catch(e => {
                            this.$Message.error("修改失败");
                        });
                    },
                });
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>